public class Exist {

    String word;
    char[][] board;
    boolean[][] flag;
    int m;
    int n;
    int[][] temp = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}};
    public boolean exist(char[][] board, String word) {
        this.board = board;
        this.word = word;
        m = board.length;
        n = board[0].length;
        flag = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (process(0, i, j)) return true;
            }
        }
        return false;
    }

    public boolean process(int i, int x, int y) {
        if (board[x][y] != word.charAt(i)) {
            return false;
        } else if (i == word.length() - 1) return true;
        flag[x][y] = true;
        for (int[] ints : temp) {
            int xx = ints[0] + x;
            int yy = ints[1] + y;
            if (xx >= 0 && xx < m && yy >= 0 && yy < n && !flag[xx][yy]) {
                if (process(i + 1, xx, yy)) return true;
            }
        }
        flag[x][y] = false;
        return false;
    }
}
